package com.oliet.exception;

import com.alibaba.fastjson.JSON;
import com.oliet.common.result.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.impl.SizeException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import javax.validation.ConstraintViolationException;

/**
 * @Title: GlobalExceptionHandler.java
 * @Description: 全局异常处理器
 * @Author: Jzp
 * @Version: （版本）
 * @Date: 2023-11-26 16:05
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Value("${spring.servlet.multipart.max-file-size}")
    private String MAX_FILE_SIZE;

    @Value("${spring.servlet.multipart.max-request-size}")
    private String MAX_REQUEST_SIZE;


    /**
     * 自定义异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomException.class)
    public CommonResponse exceptionHandler(CustomException e) {
        log.error("程序异常！原因是:", e);
        CommonResponse commonResponse = CommonResponse.error(e.getError().getCode(), e.getMessage());
        log.error("result: {}", JSON.toJSONString(commonResponse));
        return commonResponse;
    }

    /**
     * 1、参数检查异常处理
     * 2、系统未知异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public CommonResponse exceptionHandler(Exception e) {
        log.error("程序异常！原因是:", e);
        ErrorEnum error = ErrorEnum.INVALID_PARAMETER;
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            error.setMessage(ex.getBindingResult().getFieldError().getDefaultMessage());
        } else if (e instanceof BindException) {
            BindException ex = (BindException) e;
            error.setMessage(ex.getFieldError().getDefaultMessage());
        } else if (e instanceof ConstraintViolationException) {
            ConstraintViolationException ex = (ConstraintViolationException) e;
            error.setMessage(ex.getMessage());
        } else if (e instanceof FileUploadException) {
            error.setMessage("上传文件最大限制为：" + MAX_FILE_SIZE);
        } else {
            log.error("程序异常！原因是:", e);
            error = ErrorEnum.UNSPECIFIED;
        }
        CommonResponse commonResponse = CommonResponse.error(error.getCode(), error.getMessage());
        log.error("result: {}", JSON.toJSONString(commonResponse));
        return commonResponse;
    }


    /**
     * 处理文件上传相关异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MultipartException.class)
    public CommonResponse exceptionHandler(MultipartException e) {
        log.error("程序异常！原因是:", e);
        StringBuilder sb = new StringBuilder();
        sb.append("文件上传异常：").append(e.getMessage());
        sb.append("上传文件总大小限制为：").append(MAX_REQUEST_SIZE);
        sb.append("，单个文件大小限制为：").append(MAX_FILE_SIZE);
        CommonResponse commonResponse = CommonResponse.error("5000", sb.toString());
        log.error("result: {}", JSON.toJSONString(commonResponse));
        return commonResponse;
    }

}
